package com.raycloud.robot.utils;

import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import com.alibaba.dubbo.common.utils.JVMUtil;
import java.io.FileOutputStream;
import java.io.File;
import java.util.concurrent.Executors;
import org.apache.commons.lang3.StringUtils;
import java.util.concurrent.Semaphore;
import org.slf4j.Logger;

public class JVMUtils{
    public static final Logger logger;
    private static volatile long lastPrintTime;
    private static final Long TEN_MINUTES;
    private static Semaphore guard;
    public static void dumpJStack(final String path){
        final Long now=System.currentTimeMillis();
        if(now-JVMUtils.lastPrintTime<JVMUtils.TEN_MINUTES){
            return;
        }
        if(!JVMUtils.guard.tryAcquire()){
            return;
        }
        final String resultPath=StringUtils.isNotBlank(path)?path:"/home/tomcat/stack";
        Executors.newSingleThreadExecutor().execute(new Runnable(){
            @Override
            public void run(){
                final String dateStr=DateUtil.longToStr(System.currentTimeMillis());
                FileOutputStream jstackStream=null;
                try{
                    FileUtils.isChartPathExist(resultPath);
                    jstackStream=new FileOutputStream(new File(resultPath,dateStr+"\u7684\u7ebf\u7a0b\u6c60\u76d1\u63a7.log"));
                    JVMUtil.jstack((OutputStream)jstackStream);
                }
                catch(Throwable t){
                    JVMUtils.logger.error("dump jstack error",t);
                }
                finally{
                    JVMUtils.guard.release();
                    if(jstackStream!=null){
                        try{
                            jstackStream.flush();
                            jstackStream.close();
                        }
                        catch(IOException ex){
                        }
                    }
                }
                JVMUtils.lastPrintTime=System.currentTimeMillis();
            }
        });
    }
    static{
        logger=LoggerFactory.getLogger(JVMUtils.class);
        JVMUtils.lastPrintTime=0L;
        TEN_MINUTES=600000L;
        JVMUtils.guard=new Semaphore(1);
    }
}
